package com.geekhole.demo.v2.service.base;

import com.geekhole.demo.domain.Agg;
import com.geekhole.demo.domain.DomainServiceContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.repository.CrudRepository;

public abstract class AbstractUpdateService<AGG extends Agg, CONTEXT extends DomainServiceContext>
    extends AbstractDomainService<AGG, CONTEXT>{
    private final CrudRepository<AGG, ?> repository;

    private final ApplicationEventPublisher eventPublisher;

    public AbstractUpdateService(CrudRepository<AGG, ?> repository,
                                    ApplicationEventPublisher eventPublisher) {
        super(repository, eventPublisher);
        this.repository = repository;
        this.eventPublisher = eventPublisher;
    }

    @Override
    protected AGG doHandle(CONTEXT context) {
        // 1. 加载聚合根
        AGG agg = loadAgg(context);

        // 2. 验证聚合根
        if (agg == null){
            notFound(context);
        }

        // 3. 调用聚合根方法
        update(agg, context);

        // 4. 保持对象
        saveToDB(agg);

        return agg;
    }


    private void saveToDB(AGG agg) {
        this.repository.save(agg);
    }

    protected abstract void update(AGG agg, CONTEXT context);

    protected abstract void notFound(CONTEXT context);

    protected abstract AGG loadAgg(CONTEXT context);

}
